package com.xk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.core.exception.ServiceException;
import com.xk.entity.QuestionBank;
import com.xk.mapper.QuestionBankMapper;
import com.xk.service.QuestionBankService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 题库表(QuestionBank)表服务实现类
 *
 * @author YaWu
 * @since 2024-12-14 23:58:07
 */
@Service("questionBankService")
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankMapper, QuestionBank> implements QuestionBankService {

    @Override
    public List<QuestionBank> getRandomQuestions(Long questionType, Long limit) {
        if(questionType == null){
            throw  new ServiceException("questionType不能为空",500);
        }
        LambdaQueryWrapper<QuestionBank> queryWrapper= new LambdaQueryWrapper<QuestionBank>()
                .eq(QuestionBank::getQuestionType, questionType)
                .last("ORDER BY RAND() LIMIT " + limit); // 随机排序并限制数量
        List<QuestionBank> list = this.list(queryWrapper);
        if(list == null || list.size() == 0){// 当前题库类型没有题目
            throw  new ServiceException("当前题库类型:"+questionType+"没有题目",500);
        }
        if(list.size() != limit){// 剩余题目不足limit
            throw  new ServiceException("当前题库类型:"+questionType+"题库数量不足"+limit,500);
        }
        return list;
    }
}

